using System;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

using RealDolmen.SharePoint.Helpers;

namespace RealDolmen.SharePoint.ListFeatures
{
    public class ListFeatureWorkItemJobDefinition : SPWorkItemJobDefinition
    {
        #region Variables
        [Persisted]
        private string listFeatureTrackerData;

        private ListFeature tempListFeature;
        #endregion // Variables

        #region Properties
        public string ListFeatureTrackerData
        {
            get { return listFeatureTrackerData; }
            set { listFeatureTrackerData = value; }
        }

        #endregion // Properties

        #region Constructors
        public ListFeatureWorkItemJobDefinition()
            : base() { }
        public ListFeatureWorkItemJobDefinition(string name, string title, SPWebApplication webApplication, ListFeature listFeature)
            : base(name, webApplication, null, SPJobLockType.Job)
        {
        }
        #endregion // Constructors

        #region Business Methods
        public override void Execute(System.Guid targetInstanceId)
        {
            SPWeb web;
            SPSite site;
            tempListFeature = ListFeatureTracker.Instantiate(ListFeatureTrackerData).OpenListFeature(out web, out site);

            if (tempListFeature != null)
            {
                if (tempListFeature.IsActive)
                {
                    tempListFeature.Register(this);
                    base.Execute(targetInstanceId);
                    SPHelper.TryDisposeWeb(web);
                    SPHelper.TryDisposeSite(site);
                }
            }
        }
        public override void ProcessWorkItems(SPContentDatabase db, SPWorkItemCollection workItems)
        {
            ProcessWorkItems(db, workItems, tempListFeature);
        }
        public override void ProcessWorkItems(SPContentDatabase db, SPWorkItemCollection workItems, ref bool continueProcessing)
        {
            ProcessWorkItems(db, workItems, tempListFeature, ref continueProcessing);
        }
        public virtual void ProcessWorkItems(SPContentDatabase db, SPWorkItemCollection workItems, ListFeature listFeature)
        {
            throw new InvalidOperationException();
        }
        public virtual void ProcessWorkItems(SPContentDatabase db, SPWorkItemCollection workItems, ListFeature listFeature, ref bool continueProcessing)
        {
            throw new InvalidOperationException();
        }
        #endregion // Business Methods
    }
}
